package com.obixlabs.security.credentialsstore.server;

import java.rmi.RemoteException;
import java.util.List;

import javax.xml.ws.Endpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.obixlabs.security.credentialsstore.services.SecurityService;

public class WebServiceExporter
{
	private Logger logger = 
			LoggerFactory.getLogger(WebServiceExporter.class);
	
	private List<SecurityService> services;
	private Integer serverPort; 
	
	private static final String LOCALHOST_ADDRESS_PREFIX = "http://localhost:";
	private static final Integer DEFAULT_SERVER_PORT = 9001;
	
	public WebServiceExporter(){}	
	
	public void init() throws RemoteException
	{
		if (services!=null && services.size()!=0)
		{
			logger.info("Initializing " + services.size() + " web services.");			
			
			if (serverPort==null)
			{
				logger.info("Port# not specified, will use default " + 
							DEFAULT_SERVER_PORT);
				setServerPort(DEFAULT_SERVER_PORT);
			}
			
			SecurityService securityService;
			String address;
			for (Object service : services)
			{
				securityService = (SecurityService)service;
				address = getServiceAddress(securityService);
				Endpoint.publish(address, securityService);
			}
		}
	}
	
	public String getServiceAddress(
					SecurityService securityService)
					throws RemoteException
	{
		StringBuffer result = new StringBuffer(
							LOCALHOST_ADDRESS_PREFIX);
		result.append(getServerPort());
		result.append("/");
		result.append(securityService.getServiceName());
		return result.toString();
	}
	
	public void setServices(List<SecurityService> services){this.services = services;}	
	public List<SecurityService> getServices(){return services;}
	
	public void setServerPort(Integer serverPort){this.serverPort = serverPort;}
	public Integer getServerPort(){return serverPort;}
}
